package com.base.cn.platform.os.common.thread;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;

import java.util.concurrent.Executor;

/**
 * 异步线程池配置
 *
 * @author s.li
 * @date 2019/05/09
 */
@Configuration
public class AsyncExecutorConfig extends AsyncConfigurerSupport {
    /**
     * 获取异步线程池对象
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        ContextAwarePoolExecutor poolExecutor = new ContextAwarePoolExecutor();
        //获取系统CPU核数
        int processorsNum = Runtime.getRuntime().availableProcessors();
        poolExecutor.setCorePoolSize(processorsNum);//没有任务时，维护最少线程数量
        poolExecutor.setMaxPoolSize(processorsNum*140);
        poolExecutor.setQueueCapacity(processorsNum*150);
        poolExecutor.setThreadNamePrefix("async-executor-pool-");
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不再新线程中执行任务，而是由调用者所在的线程来执行
        poolExecutor.initialize();
        return poolExecutor;
    }
}
